package com.example.dense_rack_server.utils.Netty;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * 客户端，发送命令
 */
@Slf4j
@Component
public class Client {
    public JSONObject send(String sendContent, String ip, boolean isReturn) throws IOException {
        String[] ipList = ip.split(":");
        synchronized (this) {
            String result = null;
            try {
                Socket client = new Socket();
                client.connect(new InetSocketAddress(ipList[0], Convert.toInt(ipList[1])), 3000);
                client.setSoTimeout(3000);
                //获取Socket的输出流，用来发送数据到服务端
                OutputStream out = client.getOutputStream();
                //发送数据到服务端
                log.info("发送数据：" + sendContent);
                sendContent = sendContent + "\n";
                byte[] temp = sendContent.getBytes("gbk");//这里写原编码方式
                out.write(temp);
                out.flush();
                if (isReturn) {
                    //获取Socket的输入流，用来接收从服务端发送过来的数据
                    InputStream buf = client.getInputStream();
                    byte[] bytes = new byte[1024];
                    int len = buf.read(bytes);
                    result = new String(bytes, 0, len, "gbk");
                    buf.close();
                }
                out.close();
                client.close();
            } catch (SocketTimeoutException e) {
                log.info("连接超时");
            }
            JSONObject resultMap = JSONUtil.parseObj(result);
            // 获取锁状态 1 开 0 关
//            int status = get_lock_status(position, Convert.toInt(resultMap.get("addr")), Integer.parseInt(resultMap.getStr("lock_status"), 16));
//            resultMap.put("lock_status", status);
            return resultMap;
        }
    }

    public static void main(String[] args) throws IOException, InterruptedException {
        String ip = "192.168.3.7:8886";
        StringBuffer sendContent = new StringBuffer();
        Map<String, Object> map = new HashMap<>();
        map.put("adr", 0);
        map.put("cd", "scan");
        sendContent.append(JSONUtil.toJsonStr(map) + "\n");
        Map<String, Object> readMap = new HashMap<>();
        readMap.put("adr", 1);
        readMap.put("cd", "readgroup");
        sendContent.append(JSONUtil.toJsonStr(readMap));
        JSONObject rfidResult = new Client().send(sendContent.toString(), ip,true);
        System.out.println(rfidResult.toString());
    }
}
